package com.ccys.cms.service.masterData.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.masterData.ClinicService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.masterData.ClinicDto;
import com.ccys.db.entity.TblClinic;
import com.ccys.db.entity.TblPaymentMethods;
import com.ccys.db.mapper.TblClinicMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.masterData.ClinicPageQueryVo;
import com.ccys.db.vo.masterData.ClinicQueryByGroupIdVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @program: WhiteCoat
 * @description: 诊所接口实现类
 * @author: ZhangJingCan
 * @create: 2023-12-14 13:54
 **/

@Service
public class ClinicServiceImpl extends BaseServiceImpl<TblClinic> implements ClinicService {

    @Resource
    private TblClinicMapper tblClinicMapper;

    /**
     * 用于保存修改状态日志
     */
    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveClinic(ClinicDto dto) {
        //校验必传参数
        if (ObjectUtil.isEmpty(dto.getGroupId()) || ObjectUtil.isEmpty(dto.getCompanyId()) || ObjectUtil.isEmpty(dto.getName())
                || ObjectUtil.isEmpty(dto.getAddress()) || ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getLicenseNumber())
                || ObjectUtil.isEmpty(dto.getGstRegistered()) || ObjectUtil.isEmpty(dto.getLogoType()) || ObjectUtil.isEmpty(dto.getCountryId())) {
            return ResponseResult.error("Parameter error, please check the parameters!");
        }
        //根据条件检查参数
        if (dto.getGstRegistered().equals(1)) {
            if (ObjectUtil.isEmpty(dto.getGstRegistrationNo())) {
                return ResponseResult.error("GST registration no not filled in!");
            }
        }
        if (dto.getLogoType().equals(1)) {
            if (ObjectUtil.isEmpty(dto.getImage())) {
                return ResponseResult.error("Please upload pictures!");
            }
        }
        //校验是否存在同名数据：groupId - companyId - countryId - name 相等并且未删除，存在则返回错误提示
        //准备查询
        Example example = new Example(TblClinic.class);
        Example.Criteria criteria = example.createCriteria().andEqualTo("groupId", dto.getGroupId())
                .andEqualTo("companyId", dto.getCompanyId())
                .andEqualTo("countryId", dto.getCountryId())
                .andEqualTo("name", dto.getName())
                .andEqualTo("delFlag", 0);
        //如果id有值 - 属于修改 - 需要排除自身
        if (ObjectUtil.isNotEmpty(dto.getId())) {
            criteria.andNotEqualTo("id", dto.getId());
        }else {
            //新增需要生成一个默认的诊所支付方式数据
            TblPaymentMethods methods = new TblPaymentMethods();
//            methods todo
        }
        //查询并判断
        if (ObjectUtil.isNotEmpty(tblClinicMapper.selectOneByExample(example))) {
            return ResponseResult.error("This clinic name already exists!");
        }
        //以上所有校验完毕没问题 - 则开始新增/修改
        return ResponseResult.update(this.insertOrUpdate(dto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteClinic(ClinicDto dto) {
        //判断
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备实体类并赋值
        TblClinic clinic = new TblClinic();
        clinic.setId(dto.getId());
        clinic.setDelFlag(1);
        //判断是否修改成功 - 返回不同状态
        if (tblClinicMapper.updateByPrimaryKeySelective(clinic) > 0) {
            return ResponseResult.success("Delete Successful!");
        }
        return ResponseResult.error("Delete Failed!");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateClinicStatus(ClinicDto dto) {
        //校验
        if (ObjectUtil.isEmpty(dto.getId()) || ObjectUtil.isEmpty(dto.getStatus())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备数据修改
        TblClinic clinic = new TblClinic();
        clinic.setId(dto.getId());
        clinic.setStatus(dto.getStatus());
        if (tblClinicMapper.updateByPrimaryKeySelective(clinic) > 0) {
            //保存状态修改日志
            baseTblAuditTrailWebService.saveStatusLog(dto, dto.getStatus());
            return ResponseResult.success("Modified successfully!");
        }
        return ResponseResult.error("Modification failed!");
    }

    @Override
    public ResponseResult<PageInfo<ClinicPageQueryVo>, Object> findPageClinic(ClinicDto dto) {
        //校验字段值 - 不在范围则设置为null
        dto.setStatus(Optional.ofNullable(dto.getStatus()).filter(s -> s > -1 && s < 2).orElse(null));
        dto.setGstRegistered(Optional.ofNullable(dto.getGstRegistered()).filter(s -> s > -1 && s < 2).orElse(null));
        //开启分页
        PageDto.startPage();
        List<ClinicPageQueryVo> list = tblClinicMapper.findPageClinic(dto);
        PageInfo<ClinicPageQueryVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public ResponseResult<List<ClinicQueryByGroupIdVo>, Object> findListClinicByGroupId(ClinicDto dto) {
        //准备查询数据
        List<ClinicQueryByGroupIdVo> list = tblClinicMapper.findListClinicByGroupId(dto.getGroupId(), dto.getCompanyId(), dto.getDoctorId());
        return ResponseResult.success(list);
    }
}
